package com.demo.common.shiro;

import com.demo.common.model.Roles;
import com.demo.common.model.Users;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * 自定义登录验证
 */
public class ShiroDbRealm extends AuthorizingRealm {

    public String getName() {
        return "DbRealm";
    }
    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        int userId = (Integer) principals.fromRealm(getName()).iterator().next();
        Users user = Users.dao.findById(userId);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Roles role = Roles.dao.findById(user.getInt("roleid"));
            info.addRole(role.getStr("rolename"));
            // info.addStringPermissions(role.getPermissions()
            // );//如果你添加了对权限的表，打开此注释，添加角色具有的权限

            return info;
        } else {
            return null;
        }
    }
    /**
     * 认证回调函数,登录时调用.
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
            UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
            String password = String.valueOf(token.getPassword());
            // 调用操作数据库的方法查询user信息
            Users user = Users.dao.findFirst(
                    "select * from users where username = ?", token.getUsername());
            if (user != null) {
                if (password.equals(user.getStr("password"))) {
                    Session session = SecurityUtils.getSubject().getSession();
                    session.setAttribute("username", user.getStr("username"));
                    return new SimpleAuthenticationInfo(user.getInt("id"),
                            user.getStr("password"), getName());
                } else {
                    return null;
                }
            } else {
                return null;
            }
    }
}
